package chatRoom.client;

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

/**
 * 建立与服务器的连接
 * 读取服务器发送来的信息
 * 控制台上的信息发送给服务器
 */
public class Client {
    private Socket socket;
    public Client(){
        try {
            System.out.println("客户端正在连接服务器.......");
            socket=new Socket("localhost",8080);
            System.out.println("客户端成功建立与服务器的连接..........");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    public void start(){
        Thread t=new Thread(new ServerHandler(socket));
        t.start();
        try( PrintWriter pw=  new PrintWriter(new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"utf-8")),true)) {
            System.out.println("当输入exit时,退出聊天");
            Scanner scanner=new Scanner(System.in);
            String message;
            while (true){
                message=scanner.nextLine();
                if ("exit".equals(message)){
                    break;
                }
                pw.println(message);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                socket.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

    public static void main(String[] args) {
        Client client=new Client();
        client.start();
    }
}
